package com.gymmsystem.GYMMSystem.controller;

import com.gymmsystem.GYMMSystem.common.Result;
import com.gymmsystem.GYMMSystem.entity.Reservation;
import com.gymmsystem.GYMMSystem.dto.UserReservationDTO;
import com.gymmsystem.GYMMSystem.service.ReservationService;
import com.gymmsystem.GYMMSystem.common.PageResult;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/reservations")
@RequiredArgsConstructor
@CrossOrigin(origins = "${cors.allowed-origins}", allowCredentials = "true")
@Slf4j
public class ReservationController {

    @Resource
    private final ReservationService reservationService;

    // 获取用户的预约记录（旧接口，兼容现有调用）
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Map<String, Object>>> getUserReservations(@PathVariable Long userId) {
        List<Map<String, Object>> reservations = reservationService.getUserReservations(userId);
        return ResponseEntity.ok(reservations);
    }
    
    // 获取用户的预约记录（新接口，返回DTO格式）
    @GetMapping("/user/{userId}/dto")
    public ResponseEntity<List<UserReservationDTO>> getUserReservationsDTO(@PathVariable Long userId) {
        List<UserReservationDTO> reservations = reservationService.getUserReservationsDTO(userId);
        return ResponseEntity.ok(reservations);
    }

    // 获取教练的预约记录
    // 教练收到的预约列表（包含用户和课程信息）
    @GetMapping("/coach/{coachId}")
    public ResponseEntity<List<Map<String, Object>>> getCoachReservations(@PathVariable Long coachId) {
        List<Map<String, Object>> reservations = reservationService.getCoachReservations(coachId);
        return ResponseEntity.ok(reservations);
    }

    // 根据ID获取预约详情
    @GetMapping("/{reservationId}")
    public ResponseEntity<Reservation> getReservationById(@PathVariable Long reservationId) {
        Reservation reservation = reservationService.getReservationById(reservationId);
        return reservation != null ? ResponseEntity.ok(reservation) : ResponseEntity.notFound().build();
    }

    // 创建新的课程预约
    @PostMapping(path = "/create")
    public ResponseEntity<?> createReservation(@RequestBody Reservation reservation) {
        try {
            boolean success = reservationService.createReservation(reservation);
            return success ? ResponseEntity.ok("预约成功") :
                    ResponseEntity.badRequest().body("预约失败");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 取消预约
    @PutMapping("/{reservationId}/cancel")
    public ResponseEntity<?> cancelReservation(
            @PathVariable Long reservationId,
            @RequestParam String reason) {
        try {
            boolean success = reservationService.cancelReservation(reservationId, reason);
            return success ? ResponseEntity.ok("取消预约成功") :
                    ResponseEntity.badRequest().body("取消预约失败");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 确认预约
    @PutMapping("/{reservationId}/confirm")
    public ResponseEntity<?> confirmReservation(@PathVariable Long reservationId) {
        boolean success = reservationService.confirmReservation(reservationId);
        return success ? ResponseEntity.ok("确认预约成功") :
                ResponseEntity.badRequest().body("确认预约失败");
    }

    // 标记预约完成
    @PutMapping("/{reservationId}/complete")
    public ResponseEntity<?> completeReservation(@PathVariable Long reservationId) {
        boolean success = reservationService.completeReservation(reservationId);
        return success ? ResponseEntity.ok("完成预约成功") :
                ResponseEntity.badRequest().body("完成预约失败");
    }

    // 检查用户是否已预约某课程
    @GetMapping("/check")
    public ResponseEntity<Boolean> checkUserCourseReservation(
            @RequestParam Long userId,
            @RequestParam Long courseId) {
        boolean exists = reservationService.checkUserCourseReservation(userId, courseId);
        return ResponseEntity.ok(exists);
    }

    // 获取课程的活跃预约数量
    @GetMapping("/course/{courseId}/count")
    public ResponseEntity<Integer> getActiveReservationsCount(@PathVariable Long courseId) {
        int count = reservationService.getActiveReservationsCount(courseId);
        return ResponseEntity.ok(count);
    }

    // 获取待确认预约总数
    @GetMapping("/pending/count")
    public Result<?> getPendingReservationsCount() {
        return Result.success(reservationService.countPendingReservations());
    }
    
    // 一键确认所有待确认预约
    @PutMapping("/pending/confirm-all")
    public Result<?> confirmAllPendingReservations() {
        Integer count = reservationService.confirmAllPendingReservations();
        return Result.success(count);
    }

    // 获取所有预约列表（非取消状态）
    @GetMapping("/admin/active")
    public ResponseEntity<List<Map<String, Object>>> getAllActiveReservations() {
        List<Map<String, Object>> reservations = reservationService.getAllActiveReservations();
        return ResponseEntity.ok(reservations);
    }

    // 获取取消预约列表
    @GetMapping("/admin/cancelled")
    public ResponseEntity<List<Map<String, Object>>> getCancelledReservations() {
        List<Map<String, Object>> reservations = reservationService.getCancelledReservations();
        return ResponseEntity.ok(reservations);
    }
    
    /**
     * 分页获取活跃预约列表
     * @param page 当前页码，默认1
     * @param size 每页大小，默认6
     * @return 分页结果
     */
    @GetMapping("/admin/active/page")
    public ResponseEntity<Map<String, Object>> getActiveReservationsByPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "6") Integer size) {
        Map<String, Object> result = reservationService.getActiveReservationsByPage(page, size);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 分页获取取消预约列表
     * @param page 当前页码，默认1
     * @param size 每页大小，默认6
     * @return 分页结果
     */
    @GetMapping("/admin/cancelled/page")
    public ResponseEntity<Map<String, Object>> getCancelledReservationsByPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "6") Integer size) {
        Map<String, Object> result = reservationService.getCancelledReservationsByPage(page, size);
        return ResponseEntity.ok(result);
    }
}